<template>
  <div class="container">
    <div class="header">
      <div class="title">{{ title }}</div>
      <div class="btns">
        <el-button :loading="saveLoading" round @click="save"
          >保存并返回</el-button
        >
        <el-button round @click="generatePaper" v-if="allowGenerate"
          >生成试卷</el-button
        >
        <el-button round :disabled="!allowGenerate" v-else
          >已生成试卷</el-button
        >
      </div>
    </div>
    <div class="content">
      <div class="main"><MainComponent @editor-ready="editorReady" /></div>
      <div class="toolbar"><ToolbarComponent /></div>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, computed } from "vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import store from "./store";
import MainComponent from "./update-section/main.vue";
import ToolbarComponent from "./update-section/toolbar.vue";
import GeneratingComponent from "./update-section/generating.vue";
import { questionFormat } from "./../utils/question-format";
import $ from "$";

export default {
  components: { MainComponent, ToolbarComponent },
  props: ["id", "close", "title", "type"],
  setup(props) {
    let loading = ElLoading.service();

    store.commit("reset");

    let dataset = computed(() => store.state.dataSet);
    if (!props.type) {
      $.http.post("/admin/questionImportLog/queryQuestionByImportId", {
        importId: props.id,
      })
      .then((res) => {
        if (res.result) {
          let questions = res.json.questionList.map((data) =>
            questionFormat(data)
          );
          store.commit("set_error_list", res.json.failInfo);
          store.commit("set_data_set", questions);

          allowGenerate.value = !res.json.paperId;
          backList();
        } else {
          ElMessage.warning(res.msg);
          loading.close()
        }
      });
    } else {
      $.http.post("/admin/questionImportLog/queryXKWQuestion", {
        paperId: props.id,
      })
      .then((res) => {
        if (res.result) {
          let questions = res.json.questionList.map((data) =>
            questionFormat(data)
          );
          store.commit("set_error_list", res.json.failInfo);
          store.commit("set_data_set", questions);

          allowGenerate.value = !res.json.paperId;
          backList();
        } else {
          ElMessage.warning(res.msg);
          loading.close()
        }
      });
    }
    
    const backList = async () => {
      if (dataset.value.length < 1) {
        loading.close();
        await ElMessageBox.confirm(
          "当前文档未查询到题目或题目已删除。",
          "提示",
          {
            confirmButtonText: "确认",
            showClose: false,
            showCancelButton: false,
            type: "warning",
          }
        );
        props.close();
      }
    };
    let saveLoading = ref(false);
    const save = async () => {
      saveLoading.value = true;
      let questions = __cloneData(dataset.value);
      let res = await $.http.json("/tiku/question/batchSaveQuestion", {
        questionImportLogId: props.id,
        questions,
      });
      !res.result && ElMessage.warning(res.msg);
      props.close(res);
    };

    const __cloneData = (data) => {
      let questions = $.clone(data).map((data) => {
        data.questionSources &&
          data.questionSources.length &&
          data.questionSources.map((i) => {
            if (i.provinceCity && i.provinceCity.length) {
              i.provinceId = i.provinceCity[0];
              i.cityId = i.provinceCity[1] || null;
              i.areaId = i.provinceCity[2] || null;
            }
            return i;
          });
        return data;
      });

      return questions;
    };

    let allowGenerate = ref(true);
    const generatePaper = () => {
      let questions = __cloneData(dataset.value);
      $.modal
        .create({
          component: GeneratingComponent,
          title: "生成试卷",
          width: 420,
          zIndex: 2010,
          props: { questions, id: props.id },
        })
        .then((res: any) => {
          ElMessage[res.result ? "success" : "warning"](
            res.result ? "生成试卷成功" : "生成试卷失败，请重试"
          );
          allowGenerate.value = !res.result;
        });
    };

    /* -------- 子组件富文本完全渲染完毕后关闭loading -------- */
    let editorReadyNumber = 0;
    const editorReady = () => {
      editorReadyNumber === dataset.value.length - 1
        ? loading.close()
        : editorReadyNumber++;
    };

    return { save, saveLoading, generatePaper, allowGenerate, editorReady };
  },
};
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  & > .header {
    display: flex;
    height: 60px;
    line-height: 60px;
    text-align: right;
    background: #72b22a;
    box-shadow: 0px 0px 3px 0px rgba(45, 113, 183, 0.15);
    .title {
      flex: auto;
      padding: 0 40px 0 80px;
      color: #fff;
      font-size: 18px;
      text-align: left;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .btns {
      white-space: nowrap;
    }
    button {
      color: #72b22a;
      padding: 10px 23px;
      margin-right: 20px;
      margin-left: 0;
      &:last-child {
        color: #999;
      }
    }
  }
  .content {
    display: flex;
    flex: 1 1 60px;
    height: 100%;
    background: #f4f5f9;
    overflow: hidden;
    .main {
      flex: 1 1 340px;
      height: 100%;
      padding: 20px;
      overflow: auto;
    }
    .toolbar {
      width: 340px;
      height: 100%;
      background: #fff;
    }
  }
}
</style>
